{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Understanding Window Calculations\n",
    "\n",
    "## About the Data\n",
    "In this notebook, we will be working with Facebook's stock price throughout 2018 (obtained using the [`stock_analysis` package](https://github.com/stefmolin/stock-analysis)).\n",
    "\n",
    "## Interactive Visualizations\n",
    "If you follow the installation instructions [here](https://github.com/matplotlib/jupyter-matplotlib), you can run the following interactive plot to see what different window calculations look like. This requires you to install `ipyml` and `node.js` and run a few commands from the command line as indicated in the aforementioned link. Note you will need to restart the kernel.\n",
    "\n",
    "*More information on the `interact()` function can be found [here](https://ipywidgets.readthedocs.io/en/stable/examples/Using%20Interact.html).*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "555c8238c49c438289c1c676783bde85",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "interactive(children=(IntSlider(value=20, description='period', max=200, step=5), Dropdown(description='window…"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%matplotlib widget\n",
    "from ipywidgets import interact\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "\n",
    "fb = pd.read_csv('data/fb_2018.csv', index_col='date', parse_dates=True)\n",
    "\n",
    "def window_calculations(df):\n",
    "    def plot_viz(period=20, window_type='rolling', agg='mean'):\n",
    "        ax = df.plot(y='close')\n",
    "        window_func = getattr(df.close, window_type)\n",
    "        if window_type == 'rolling':\n",
    "            kwargs = {'window': period}\n",
    "        elif window_type == 'expanding':\n",
    "            kwargs = {'min_periods': period}\n",
    "        elif window_type == 'ewm':\n",
    "            kwargs = {'span': period}\n",
    "            if agg != 'mean':\n",
    "                print('Changing to mean')\n",
    "                agg = 'mean'\n",
    "        window_func(**kwargs).agg(agg).plot(ax=ax, label=f'{window_type} {period}D {agg}')\n",
    "\n",
    "        plt.suptitle('Window Calculations on Facebook Closing Price')\n",
    "        plt.title('(Note: EWM only works with mean)')\n",
    "        plt.ylabel('price ($)')\n",
    "        plt.legend()\n",
    "    \n",
    "    return plot_viz\n",
    "interact(\n",
    "    window_calculations(fb), \n",
    "    period=(0, 200, 5), \n",
    "    window_type=['rolling', 'expanding', 'ewm'], \n",
    "    agg=['sum', 'min', 'max', 'mean']\n",
    ");"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
